<template>
<div class="body">
  <div class="container m1">
    <h1 style="font-weight: bold;">书生AI问答</h1>
    <div id="scrollRef" ref="scrollRef">
      <div :key="key1">
        <div class="qa-pair" v-for="(item,index) in messageList">
          <div class="line1">
            <div class="question-icon">❓</div>
            <div class="question">{{ item.self }}</div>
          </div>
          <div class="line2">
            <div class="answer-icon">✅</div>
            <div class="answer">{{ item.robot }}</div>
          </div>
        </div>
      </div>
      <div class="qa-pair" v-if="messageList.length === 0">
        <div class="line2">
          <div class="answer-icon">✅</div>
          <div class="answer">
            <b>你好，我是智能AI问答</b><br>
            作为你的智能伙伴，我既能写文案、想点子，又能陪你聊天、答疑解惑。
            你可以试着向我提问，我会尽力回答。
          </div>
        </div>
      </div>
    </div>
    <div class="button-content">
      <button class="clear" @click="clear">清空</button>
    </div>
  </div>
  <div class="container m2">
    <div class="text-content">
      <textarea class="textarea" v-model="userInput" :placeholder="placeholder"></textarea>
      <div class="button-content">
        <button class="submit" :class="{'disabled': disabled }" @click="sendQuestion">发送</button>
      </div>
    </div>
    <div class="tip">内容由AI生成，无法确保真实准确，仅供参考</div>
  </div>
</div>

</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
import {callChat} from "./agentsFlex.api";
import {useGlobSetting} from "@/hooks/setting";

export default defineComponent({
  setup() {
    const globSetting = useGlobSetting();
    const baseUploadUrl = globSetting.uploadUrl;
    const URL = `${baseUploadUrl}/ai/agentsFlex/stream`;
    const userInput = ref('');
    const messageList = ref([]) as any;

    let placeholder = ref('请输入您的问题');
    let key = 1;  //  列表key
    let key1 = ref(1);  //  问答组件key
    let disabled = ref(false);  //  按钮可用状态
    let length1 = ref(0);  //  答案之前长度
    let length2 = ref(0);  //  答案之后长度
    // 发送问题函数
    async function sendQuestion() {
      if(!userInput.value || disabled.value){
        return false;
      }
      length1.value = 0;
      length2.value = 0;
      disabled.value = true;
      placeholder.value = '正在回答中。。。';
      key1.value = 1;
      let currentObj = {
        key: key,
        self: '',
        robot: '',
      }
      let isHave = false; //  回答是否是已经有的问题
      let str = ''; //  回答
      var eventSource = new EventSource(URL);

      if (userInput.value) {
        currentObj.self = userInput.value;
        // 调用AI API 获取回复
        callChat({speak : userInput.value}).then((r) => {
          userInput.value = '';
        });
        eventSource.onmessage = function(event) {
          str += event.data
          currentObj.robot = str;

          for(let i = 0; i < messageList.value.length; i++){
            if (messageList.value[i].key === currentObj.key) {
              messageList.value[i].robot = str;
              isHave = true
            }
          }
          if(!isHave){
            messageList.value.push(currentObj)
            key++;
          }
          key1.value++;
          scrollToBottom();
          length2.value = str.length;
        };

        eventSource.onerror = function(error) {
          //console.error('Error occurred:', error);
        };
      }
      userInput.value = '';
    }

    const clear = () => {
      messageList.value = [];
    };

    const scrollToBottom = () => {
      const scrollRefElement = document.querySelector('#scrollRef');
      if (scrollRefElement) {
        scrollRefElement.scrollTop = scrollRefElement.scrollHeight;
      }
    };

    let index = null as any;
    watch(
      ()=> length2.value,
      (new1, old1)=>{
        if(new1 > length1.value){
          length1.value = new1;
          clearTimeout(index)
          index = setTimeout(()=>{
            if(length1.value === length2.value){
              disabled.value = false;
              placeholder.value = '请输入您的问题';
            }
          },1000)
        }
      }
    )
    return {
      userInput,
      sendQuestion,
      messageList,
      key1,
      clear,
      disabled,
      length1,
      length2,
      placeholder,
    };
  },
});
</script>
<style lang="scss" scoped>
.body{
  font-family: 'Noto Sans', 'Arial', sans-serif;  
//  background: linear-gradient(to right, #f4f4f4, #fff);  
  margin: 0;  
  padding: 0;  
  color: #333;  
  overflow-x: hidden; /* 防止横向滚动 */  
  overflow-y: auto; /* 防止横向滚动 */  
  height: 100vh;
}
.container {
  max-width: 1000px;
  min-width: 350px;
  margin: 20px auto;
  padding: 30px;
  background-color: #fff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  position: relative;
}
.m1{
  height: calc(100vh - 300px);
  b{
    font-size: 18px;
    line-height: 24px;
  }
  #scrollRef{
    height: calc(100vh - 400px);
    overflow-y: auto;
  }
  .button-content{
    height: 42px;
    .clear{
      background: linear-gradient(to right, #9af, #9ea);
      margin: -45px 12px;
      font-size: 14px;
      text-align: center;
      padding: 8px 20px;
      cursor: pointer;
      color: #fff;
      border-radius: 20px;
      user-select: none;
      box-shadow: 4px 4px 4px 2px rgba(0,0,0,0.3);
      outline: none;
      float: right;
      border:none;
    }
  }
}
.m2{
  .tip{
    height: 1px;
    font-size: 14px;
    color: #999;
  }
}
h1 {
  text-align: center;
  color: #333;
  font-size: 24px;
  margin-bottom: 30px;
}
.qa-pair {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  align-items: flex-start;
  /* 使图标与文本垂直对齐 */
}
.line1,
.line2 {
  display: flex;
}
.line2 {
  margin-top: 10px;
}
.question-icon,
.answer-icon {
  font-size: 14px;
  color: #777;
  margin-right: 10px;
  transition: transform 0.2s ease;
  /* 添加过渡动画 */
  float: left;
  line-height: 24px;
}
.question {
  font-weight: bold;
  color: #4CAF50;
  font-size: 18px;
  float: left;
  text-align: left;
}
.answer {
  line-height: 1.6;
  float: left;
  font-size: 14px;
  text-align: left;
}

.text-content{
  border:1px solid #4CAF50;
  border-radius: 10px;
  .textarea{
    font-family: 'Noto Sans', 'Arial', sans-serif;  
    width: calc(100% - 21px);
    margin: 10px 10px 0;
    height: 44px;
    outline: none;
    border:none;
    resize:none;
    font-size: 16px;
  }
  .button-content{
    height: 42px;
    .submit{
      background: linear-gradient(to right,#00D26A, #4CAF50);
      margin: -10px 12px;
      font-size: 16px;
      text-align: center;
      padding: 8px 20px;
      cursor: pointer;
      color: #fff;
      border-radius: 20px;
      user-select: none;
      box-shadow: 4px 4px 4px 2px rgba(0,0,0,0.3);
      outline: none;
      float: right;
      border:none;
    }
    .submit:active{
      transform: rotateX(-12px);
      box-shadow: 2px 2px 4px 2px rgba(0,0,0,0.3);
    }
    .disabled{
      background: linear-gradient(to right,#aaa, #ccc );
    }
  }
}

</style>
